package com.winit.commons.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * http请求工具类
 * Created by wangjian on 16/10/9.
 */
public class HttpClientUtil {

    private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    private final static String DEFAULT_CHARSET = "UTF-8";

    /**
     * 发送http get 请求  返回字符串
     *
     * @param url
     * @return
     * @throws Exception
     */
    public static String doGet(String url) throws Exception {

        String rtnStr = "";

        if (StringUtils.isEmpty(url)) {
            logger.error("com.winit.common.util.HttpClientUtil.doGet url为空");
            throw new Exception("发送http get请求,url为空.");
        }

        CloseableHttpClient httpClient = null;
        HttpGet httpGet = null;
        CloseableHttpResponse response = null;

        try {
            httpClient = HttpClients.createDefault();
            httpGet = new HttpGet(url);
            response = httpClient.execute(httpGet);
            HttpEntity httpEntity = response.getEntity();
            if (httpEntity != null) {
                rtnStr = EntityUtils.toString(httpEntity);
            }
        } catch (Exception e) {
            logger.error("com.winit.common.util.HttpClientUtil.doGet 发送http get请求异常", e);
            throw new Exception("发送http get请求异常," + e.getMessage());
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpGet != null) {
                    httpGet.releaseConnection();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception e) {
                logger.warn("com.winit.common.util.HttpClientUtil.doGet 发送http get请求,关闭连接异常。", e);
            }
        }
        logger.info("com.winit.common.util.HttpClientUtil.doGet url=" + url + ",返回:" + rtnStr);
        return rtnStr;
    }

    /**
     * 发送http get 请求  返回json
     *
     * @param url
     * @return
     * @throws Exception
     */
    public static JSONObject doGetForJson(String url) throws Exception {
        String str = doGet(url);
        if (StringUtils.isEmpty(str)) {
            return null;
        }
        return JSONObject.parseObject(str);
    }


    public static String doPost(String url, String json) throws Exception {

        String rtnStr = "";

        if (StringUtils.isEmpty(url)) {
            logger.error("com.winit.common.util.HttpClientUtil.doPost url为空");
            throw new Exception("发送http post请求,url为空.");
        }

        CloseableHttpClient httpClient = null;
        HttpPost httpPost = null;
        CloseableHttpResponse response = null;

        try {
            httpClient = HttpClients.createDefault();
            httpPost = new HttpPost(url);
            httpPost.setHeader("Content-type", "application/json");
            if (null != json) {
                StringEntity requestEntity = new StringEntity(json, "utf-8");
                requestEntity.setContentEncoding("UTF-8");
                httpPost.setEntity(requestEntity);
            }
            response = httpClient.execute(httpPost);
            HttpEntity httpEntity = response.getEntity();
            if (httpEntity != null) {
                rtnStr = EntityUtils.toString(httpEntity);
            }
        } catch (Exception e) {
            logger.error("com.winit.common.util.HttpClientUtil.doPost 发送http post请求异常", e);
            throw new Exception("发送http post请求异常," + e.getMessage());
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpPost != null) {
                    httpPost.releaseConnection();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception e) {
                logger.warn("com.winit.common.util.HttpClientUtil.doPost 发送http psot请求,关闭连接异常。", e);
            }
        }
        logger.info("com.winit.common.util.HttpClientUtil.doPost url=" + url + ",返回:" + rtnStr);
        return rtnStr;
    }

    public static JSONObject doPostForJson(String url, String json) throws Exception {
        String str = doPost(url, json);
        if (StringUtils.isEmpty(str)) {
            return null;
        }
        return JSONObject.parseObject(str);
    }

    public static String doPost(String url, Map<String, String> params) throws Exception {
        return doPost(url, params, DEFAULT_CHARSET);
    }

    public static String doPost(String url, Map<String, String> params, String charset) throws Exception {
        if (StringUtils.isEmpty(url)) {
            logger.error("com.winit.common.util.HttpClientUtil.doPost url为空");
            throw new Exception("发送http post请求,url为空.");
        }
        logger.info("doPost:" + url + ",params:" + params + "charset:" + charset);
        charset = StringUtils.isEmpty(charset) ? DEFAULT_CHARSET : charset;
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            client = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            if (null != params && params.size() > 0) {
                List<NameValuePair> requestParams = new ArrayList<NameValuePair>();
                for (Map.Entry<String, String> param : params.entrySet()) {
                    requestParams.add(new BasicNameValuePair(param.getKey(), param.getValue()));
                }
                httpPost.setEntity(new UrlEncodedFormEntity(requestParams, charset));
            }
            response = client.execute(httpPost);
            if (response.getStatusLine().getStatusCode() != 200) {
                String msg = "http response code:" + response.getStatusLine().getStatusCode();
                logger.error(msg);
                throw new Exception(msg);
            }
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                return EntityUtils.toString(entity, charset);
            }
            return null;
        } finally {
            try {
                client.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
            try {
                response.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }

    public static void main(String[] args) {
        try {
            JSONObject param1 = new JSONObject();
            param1.put("name","build_param_1");
            param1.put("value","1");
            JSONObject param2 = new JSONObject();
            param2.put("name","build_param_2");
            param2.put("value","22222");
            List list = new ArrayList();
            list.add(param1);
            list.add(param2);

            JSONObject json = new JSONObject();
            json.put("parameter",list);

            JSONObject param = new JSONObject();
            param.put("json",json);

//curl -X POST http://192.168.56.111:8080/job/test-pip/build --data-urlencode json='{"parameter": [{"name":"build_param_1", "value":"123"}, {"name":"build_param_2", "value":"high"}]}'

            HttpClientUtil.doPost("http://192.168.56.111:8080/job/test-pip/buildWithParameters", json.toJSONString());
//            HttpClientUtil.doGet("http://192.168.56.111:8080/job/test-pip-no-param/build");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
